package com.xiaomaoguai.fcp.pre.kepler.glue.service.impl;

import com.xiaomaoguai.fcp.pre.kepler.glue.config.GlueConfig;
import com.xiaomaoguai.fcp.pre.kepler.glue.repository.GlueRepository;
import com.xiaomaoguai.fcp.pre.kepler.glue.service.GlueInitService;
import com.xiaomaoguai.fcp.pre.kepler.glue.utils.SpringContextHolder;
import com.xiaomaoguai.fcp.pre.kepler.glue.utils.extension.ExtensionLoader;
import lombok.extern.slf4j.Slf4j;

/**
 * @author WeiHui-Z
 * @version v1.0.0
 * @date 2019/9/23 19:18
 * @since JDK 1.8
 */
@Slf4j
public class GlueInitServiceImpl implements GlueInitService {

	/**
	 * 初始化扩展点
	 *
	 * @param glueConfig {@linkplain com.xiaomaoguai.fcp.pre.kepler.glue.config.GlueConfig}
	 */
	@Override
	public void initialization(GlueConfig glueConfig) {
		try {
			GlueRepository glueRepository = loadSpiSupport(glueConfig);
			glueRepository.init(glueConfig);
		} catch (Exception ex) {
			log.error("glue init exception", ex);
			System.exit(1);
		}
	}

	/**
	 * 根据配置加载不同的扩展
	 *
	 * @param glueConfig 系统配置
	 * @return GlueRepository 逻辑存储的地方
	 */
	private GlueRepository loadSpiSupport(GlueConfig glueConfig) {
		//spi repository
		final GlueRepository repository = ExtensionLoader.getExtensionLoader(GlueRepository.class)
				.getActivateExtension(glueConfig.getRepositorySupport());
		SpringContextHolder.registerBean(GlueRepository.class.getName(), repository);
		return repository;
	}

}
